<?php
class Message
{
    private $subject        = '';
    private $body           = '';
    private $priority       = 3;
    private $error          = false;

    public function __construct($locale, $template, $data)
    {
        $template = Template::getOne($locale, $template);

        if (empty($template))
        {
            $this->error = 'Template "' . $template . '" (' . $locale . ') - not found';

            return false;
        }
        else
        {
            $this->subject = $template['subject'];
            $this->body = $template['body'];

            foreach ($data as $k => $v)
            {
                $k = '%'.$k.'%';
                $this->subject = str_replace($k, $v, $this->subject);
                $this->body = str_replace($k, $v, $this->body);
            }

            return true;
        }
    }

    public function getError()
    {
        return $this->error;
    }

    public function send($email)
    {
        if ($this->error === false)
        {
            $result = Mailer::sendMessage(
                $email,
                $this->subject,
                $this->body,
                $this->priority
            );

            if ($result === false)
            {
                $this->error = Mailer::getError();
            }

            return $result;
        }

        return false;
    }

    public function queue($email)
    {
        return Queue::add($email, $this->subject, $this->body);
    }
}
